package com.mengchengnet.chaperonage.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.mengchengnet.chaperonage.BaseActivity;
import com.mengchengnet.chaperonage.R;
import com.mengchengnet.chaperonage.adapter.newCityAdapter;
import com.mengchengnet.chaperonage.cacheservice.CitySvc;
import com.mengchengnet.chaperonage.domain.base.CityItem;
import com.mengchengnet.chaperonage.util.PreferenceUtil;
import com.mengchengnet.chaperonage.util.Url;
import com.mengchengnet.chaperonage.view.widget.ContactItemInterface;
import com.mengchengnet.chaperonage.view.widget.ContactListViewImpl;
import com.mengchengnet.chaperonage.view.widget.pinyin.PinYin;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 选择城市
 */
public class ChooseCityActivity extends BaseActivity implements TextWatcher{

    private Context context_ = ChooseCityActivity.this;
    private EditText searchBox;
    private String searchString;

    private ContactListViewImpl listview;
    private List<ContactItemInterface> contactList=new ArrayList<>();
    boolean inSearchMode = false;
    List<ContactItemInterface> filterList;
    private SearchListTask curSearchTask = null;
    private RequestQueue requestQueue;
    newCityAdapter adapter;
    private Object searchLock = new Object();
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            listview= (ContactListViewImpl) findViewById(R.id.cityList);
            adapter=new newCityAdapter(getApplication(),R.layout.city_item, contactList);
            listview.setFastScrollEnabled(true);
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView parent, View v, int position,
                                        long id)
                {
                    List<ContactItemInterface> searchList = inSearchMode ? filterList
                            : contactList;

                    CitySvc.setSelectedCity(contactList.get(position).getCityId());
                    Intent intent = new Intent();
                    intent.putExtra("SelectedCity", contactList.get(position).getDisplayInfo());
                    intent.putExtra("id",contactList.get(position).getCityId());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_city);
        toolbarState = TOOLBAR_STYLE_BACK_TITLE;
        initToolbar("选择城市");
        requestQueue= Volley.newRequestQueue(getApplication());

        filterList = new ArrayList<ContactItemInterface>();

        getCityList();
        searchBox = (EditText) findViewById(R.id.input_search_query);
        searchBox.addTextChangedListener(this);

    }

    /**
     * 获取城市列表
     */
    private void getCityList(){
        StringRequest request = new StringRequest(Request.Method.POST, Url.GetCityList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String result) {
                        Log.e("欢迎界面", "获取城市列表接口返回值："+result );
                        JSONObject jsonObject;
                        try {
                            if(result != null && result.startsWith("\ufeff"))
                            {
                                result =  result.substring(1);
                            }
                            jsonObject = new JSONObject(result);
                            if (jsonObject.getString("code").equals("00")){
                                // Toast.makeText(WelcomeActivity.this, "获取城市列表成功", Toast.LENGTH_SHORT).show();
                                JSONArray array=jsonObject.getJSONArray("cityList");
                                for (int i = 0; i < array.length(); i++) {
                                    JSONObject obj=array.getJSONObject(i);
                                    String cityName=obj.getString("cityName");
                                    String cityId=obj.getString("cityId");
//                                    City city = new City();
//                                    city.setCityId(cityId);
//                                    city.setCityName(cityName);
//                                    city.setFullName(PinYin.getPinYin(cityName));
//                                    cityList.add(city);
                                    contactList.add(new CityItem(cityName, PinYin.getPinYin(cityName),cityId));
                                }
                                handler.sendEmptyMessage(0);


                            }
                            else {

                                Toast.makeText(ChooseCityActivity.this,"defeat",Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                Toast.makeText(ChooseCityActivity.this, "网络异常,请稍后重试！", Toast.LENGTH_SHORT).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("version", PreferenceUtil.getString(getApplication(),"versionCode"));
                return map;
            }
        };
        request.setTag("GetFenZu");
        request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, // 默认超时时间，应设置一个稍微大点儿的
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, // 默认最大尝试次数
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(request);

    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        searchString = searchBox.getText().toString().trim().toUpperCase();

        if (curSearchTask != null && curSearchTask.getStatus() != AsyncTask.Status.FINISHED)
        {
            try
            {
                curSearchTask.cancel(true);
            } catch (Exception e)
            {
                Log.i("chooseActivity", "Fail to cancel running search task");
            }

        }
        curSearchTask = new SearchListTask();
        curSearchTask.execute(searchString);
    }


    private class SearchListTask extends AsyncTask<String, Void, String>
    {

        @Override
        protected String doInBackground(String... params)
        {
            filterList.clear();

            String keyword = params[0];

            inSearchMode = (keyword.length() > 0);

            if (inSearchMode)
            {
                // get all the items matching this
                for (ContactItemInterface item : contactList)
                {
                    CityItem contact = (CityItem) item;

                    boolean isPinyin = contact.getFullName().toUpperCase().indexOf(keyword) > -1;
                    boolean isChinese = contact.getNickName().indexOf(keyword) > -1;

                    if (isPinyin || isChinese)
                    {
                        filterList.add(item);
                    }

                }

            }
            return null;
        }

        protected void onPostExecute(String result)
        {

            synchronized (searchLock)
            {

                if (inSearchMode)
                {

                    newCityAdapter adapter = new newCityAdapter(context_,R.layout.city_item, filterList);
                    adapter.setInSearchMode(true);
                    listview.setInSearchMode(true);
                    listview.setAdapter(adapter);
                    listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
                    {
                        @Override
                        public void onItemClick(AdapterView parent, View v, int position,
                                                long id)
                        {
                            List<ContactItemInterface> searchList = inSearchMode ? filterList
                                    : contactList;

                            CitySvc.setSelectedCity(contactList.get(position).getCityId());
                            Intent intent = new Intent();
                            intent.putExtra("SelectedCity", searchList.get(position).getDisplayInfo());
                            intent.putExtra("id",searchList.get(position).getCityId());
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    });
                } else
                {
                    newCityAdapter adapter = new newCityAdapter(context_,R.layout.city_item, contactList);
                    adapter.setInSearchMode(false);
                    listview.setInSearchMode(false);
                    listview.setAdapter(adapter);
                    listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
                    {
                        @Override
                        public void onItemClick(AdapterView parent, View v, int position,
                                                long id)
                        {
                            List<ContactItemInterface> searchList = inSearchMode ? filterList
                                    : contactList;

                            CitySvc.setSelectedCity(contactList.get(position).getCityId());
                            Intent intent = new Intent();
                            intent.putExtra("SelectedCity", searchList.get(position).getDisplayInfo());
                            intent.putExtra("id",searchList.get(position).getCityId());
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    });
                }
            }

        }
    }
}
